//
//  TravelingViewController.m
//  PTravel
//
//  Created by dllo on 15/11/24.
//  Copyright © 2015年 李涵. All rights reserved.
//

#import "TravelingViewController.h"

@interface TravelingViewController ()<UITableViewDataSource, UITableViewDelegate,UISearchResultsUpdating,UISearchBarDelegate,UIBarPositioning, UITextInputTraits>
@property (retain, nonatomic)UITableView *myTableView;
@property (retain, nonatomic)NSMutableArray *wordArr;//字母数组
@property (retain, nonatomic)NSMutableArray *cityArr;//拼音数组
@property (retain, nonatomic)UISearchBar *searchbar;
@property(nonatomic,retain)UISearchController *searchController;
@property(nonatomic,retain)NSMutableArray *searchArray;
@property(nonatomic,assign)NSInteger myIndex;
@property (retain, nonatomic)NSMutableAttributedString *attrituteStringenname;
@property (retain, nonatomic)NSMutableAttributedString *attrituteStringcnname;

@end

@implementation TravelingViewController

- (void)dealloc
{
    [_myTableView release];
    [_wordArr release];
    [_cityArr release];
    [_searchbar release];
    [_searchController release];
    [_searchArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor whiteColor];
    self.searchArray = [NSMutableArray array];
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时候隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(20, 64, BOUNDS.size.width, 44.0);
    //    [searchBar sizeToFit]:设置searchBar位置自适应
    [self.searchController.searchBar sizeToFit];
//    [self addChildViewController:self.searchController];
//    [self.view addSubview:self.searchController.searchBar];
    self.automaticallyAdjustsScrollViewInsets = YES;
    [self.searchController.searchBar resignFirstResponder];
    [_searchController release];

    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancelAction)];
    
    self.navigationItem.title = @"选择城市";

    
    //tableView
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, BOUNDS.size.height) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    //self.myTableView.sectionIndexColor = [UIColor colorWithRed:0.000 green:0.467 blue:0.000 alpha:1.000];
    [self.myTableView registerClass:[CityTableViewCell class] forCellReuseIdentifier:@"CityTableViewCell"];
    self.myTableView.tableHeaderView = self.searchController.searchBar;
    [self.view addSubview:self.myTableView];
    [_myTableView release];
    
    [self getData];
}


- (void)cancelAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        
        
    }];
}

- (void)getData
{
    self.cityArr = [NSMutableArray array];
    [AppTools getAFN:@"http://open.qyer.com/qyer/hotel/hot_city_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=199&lat=38.88255639279708&lon=121.5396443687879&oauth_token=7a1da33fff703bde846a4d6980671677&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%25209.1&track_user_id=7017902&v=1" block:^(id result) {
        self.wordArr = [NSMutableArray arrayWithObjects:@"Hot",@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"J", @"K", @"L", @"M", @"N", @"P", @"Q", @"R", @"S", @"T", @"W", @"X", @"Y", @"Z", nil];
        NSMutableDictionary *bigDic = result;
        NSMutableArray *arr = [bigDic objectForKey:@"data"];
        //NSMutableArray *self.cityArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in arr) {
            TotalCity *city = [[TotalCity alloc] init];
            [city setValuesForKeysWithDictionary:dic];
            [self.cityArr addObject:city];
        }
        
        [self.myTableView reloadData];
        for (int i = 0; i < self.cityArr.count-1; i++) {
            for (int j = 0; j < self.cityArr.count -1- i; j++) {
                if ([[[self.cityArr objectAtIndex:j] pinyin] compare:[[self.cityArr objectAtIndex:j+1] pinyin]] > 0) {
                    TotalCity *temp = self.cityArr[j+1];
                    self.cityArr[j+1] = self.cityArr[j];
                    self.cityArr[j] = temp;
                }
            }
        }
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.searchController.active) {
        return 1;
    }else{
        
        return self.wordArr.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchController.active) {
        return self.searchArray.count;
    }else{
        
        NSInteger hot = 0;
        for (TotalCity *cc in self.cityArr) {
            if (cc.is_hot == true) {
                hot++;
            }
        }
        NSInteger item = 0;
        for (TotalCity *cc in self.cityArr) {
            NSString *str = [cc.pinyin substringToIndex:1];
            if ([self.wordArr[section] isEqualToString:str.uppercaseString]) {
                item++;
            }
        }
        if (section == 0) {
            return hot;
        }else{
            
            return item;
        }
    }
}
#pragma mark === cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    CityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CityTableViewCell" forIndexPath:indexPath];
    if (!self.searchController.active) {
        NSMutableArray *item = [NSMutableArray array];
        if (indexPath.section == 0) {
            for (TotalCity *cc in self.cityArr) {
                if (cc.is_hot == true) {
                    [item addObject:cc];
                }
            }
        }else{
            
            for (TotalCity *cc in self.cityArr) {
                NSString *str = [cc.pinyin substringToIndex:1];
                if ([self.wordArr[indexPath.section] isEqualToString:str.uppercaseString]) {
                    [item addObject:cc];
                }
            }
        }

        cell.city = [item objectAtIndex:indexPath.row];
    }else{
        cell.city = [self.searchArray objectAtIndex:indexPath.row];
//        cell.cname.attributedText = self.attrituteStringcnname;
        cell.ename.attributedText = self.attrituteStringenname;
    }
    
    return cell;
}

#pragma mark === 表头
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.searchController.active) {
        return @"";
    }else{
        return [self.wordArr objectAtIndex:section];
    }
}


- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.wordArr;
}

//cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

#pragma === tableview点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TotalCity *c = nil;
    NSMutableArray *item = [NSMutableArray array];
    if (indexPath.section == 0) {
        for (TotalCity *cc in self.cityArr) {
            if (cc.is_hot == true) {
                [item addObject:cc];
            }
        }
    }else{
        
        for (TotalCity *cc in self.cityArr) {
            NSString *str = [cc.pinyin substringToIndex:1];
            if ([self.wordArr[indexPath.section] isEqualToString:str.uppercaseString]) {
                [item addObject:cc];
            }
        }
    }

    if (self.searchController.active) {
       c = [self.searchArray objectAtIndex:indexPath.row];
    }else{
        c = [item objectAtIndex:indexPath.row];

    }
    
    [[NSUserDefaults standardUserDefaults] setValue:c.cnname forKey:@"isTravel"];
    [[NSUserDefaults standardUserDefaults] setValue:c.lat forKey:@"lat"];
    [[NSUserDefaults standardUserDefaults] setValue:c.lng forKey:@"lng"];
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *searchString = [self.searchController.searchBar text];
    NSLog(@"===%@",searchString);
    
    [self.searchArray removeAllObjects];
    for (TotalCity *city in self.cityArr) {
        
        //rangeOfString:方法是在movieName中搜索是否包含searchText
        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
        //NSNotFound 表示请求操作的某个内容没有发现
        if ([city.enname rangeOfString:searchString].location != NSNotFound  || [city.cnname rangeOfString:searchString].location != NSNotFound ) {
            self.attrituteStringenname = [[NSMutableAttributedString alloc] initWithString:city.enname];
            self.attrituteStringcnname = [[NSMutableAttributedString alloc] initWithString:city.enname];
            NSRange range = [city.enname rangeOfString:searchString];
            [self.attrituteStringenname setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:20.0]} range:range];
            [self.attrituteStringcnname setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:20.0]} range:range];
            [self.searchArray addObject:city];
        }
    }
    NSLog(@"searchArray===%@",self.searchArray);
    
    [self.myTableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
